<?php
namespace app\extra;

use think\Validate;

class BaseValidate extends Validate
{
    /**
     * 根据数据的值是否存在验证该数据的正确性
     * @param $data
     * @return bool
     */
    public function checkRuleByData($data){
        $rule = $this->getRuleByData($data);
        $this->make($rule);
        if (!$this->check($data, $rule)) {
            return false;
        }
        return true;
    }
    /**
     * 根据数据获取验证规则
     * @param $data
     * @return array
     */
    public function getRuleByData($data){
          $keys = array_keys($data);
          return $this->getRuleList($keys);
    }

    /**
     * 通过keys获取验证规则
     * @param $keys
     * @return array
     */
    public function getRuleList($keys){
        $data = [];
        foreach ($this->rule as $key => $rule) {
            if (strpos($key, '|')) {
                // 字段|描述 用于指定属性名称
                list($field, $title) = explode('|', $key);
            } else {
                $field = $key;
            }
            if (in_array($field, $keys)){
                $data[$key] = $rule;
            }
        }
        return $data;
    }

}